package com.demo.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.core.constants.HttpStatus;
import com.demo.core.exception.BusinessException;
import com.demo.core.exception.ParameterException;
import com.demo.dao.FileDao;
import com.demo.dao.PracticalAchievementDao;
import com.demo.domain.PracticalAchievementFile;
import com.demo.service.FileService;
import com.demo.service.PracticalAchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class FileServiceImpl extends ServiceImpl<FileDao, PracticalAchievementFile> implements FileService {
    @Autowired
    FileDao fileDao;

    @Autowired
    PracticalAchievementDao practicalAchievementDao;


    /**
     * 根据MD5查询文件
     *
     * @param md5
     * @return
     */
    @Override
    public PracticalAchievementFile getFileByMd5(String md5) {
        LambdaQueryWrapper<PracticalAchievementFile> queryWrapper =
                new LambdaQueryWrapper<>();
        queryWrapper.eq(PracticalAchievementFile::getFMd5, md5);
        List<PracticalAchievementFile> list = this.list(queryWrapper);
        return list.size() == 0 ? null : list.get(0);
    }


    @Override
    public boolean uploadFile(MultipartFile[] files, long paId) throws IOException {
        if (files == null || files.length <= 0 || files[0].isEmpty() || paId == 0) {
            throw new BusinessException(HttpStatus.PARAMS_ERROR, "上传的文件为空或paid为空!");
        }
        for (int i = 0; i < files.length; i++) {
            //获取文件大小
            long size = files[i].getSize();
            //获取文件名后缀
            String fileSuffix =
                    FileUtil.getSuffix(files[i].getOriginalFilename());
            //判断文件格式是否正确
            if (size > 5 * 1024 * 1024) {
                throw new IllegalArgumentException("图片大小不能超过5MB");
            }
            //验证文件格式是否正确
            if (!Arrays.asList("jpg", "png", "pdf").contains(fileSuffix.toLowerCase())) {
                throw new IllegalArgumentException("文件类型错误，仅支持JPG、PNG、PDF格式的文件");
            }
            //生成唯一的文件名，避免冲突
            String originalFilename = StringUtils.cleanPath(files[i].getOriginalFilename());
            System.out.println("uriginalFilename:" + originalFilename);
            String uniqueFilename = UUID.randomUUID().toString() + "_" + originalFilename;
            //设置文件保存路径，这里假设保存在项目的资源文件夹中
//            String uploadDir = System.getProperty("user.dir") + "/tb_file/";
            String uploadDir = "src/main"
                    + "/resources/static"
                    + "/tb_file/";
            Path uploadPath =
                    Paths.get(uploadDir);
            //判断保存路径是否存在，如不存在，则创建文件夹
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            //文件的最终保存路径
            Path filePath =
                    uploadPath.resolve(uniqueFilename);
            //设置文件的url路径
            String uploadfileUrl;
            String md5 = SecureUtil.md5(files[i].getInputStream());
            // 从数据库查询是否存在相同的记录
            PracticalAchievementFile dbFiles = this.getFileByMd5(md5);
            // 保存文件到项目的资源文件夹
            Files.write(filePath, files[i].getBytes());
            // 拼接文件访问路径
            uploadfileUrl = "http"
                    + "://localhost:8081"
                    + "/tb_file/" + uniqueFilename;
            //存储至数据库
            PracticalAchievementFile savePracticalAchievementFile =
                    new PracticalAchievementFile();
            //获取当前上传文件的时间
            LocalDateTime uploadTime =
                    LocalDateTime.now();
            savePracticalAchievementFile.setFName(files[i].getOriginalFilename());
            savePracticalAchievementFile.setFType(fileSuffix);
            savePracticalAchievementFile.setFSize(size / 1024);//转成kb
            savePracticalAchievementFile.setFUrl(uploadfileUrl);
            savePracticalAchievementFile.setFMd5(md5);
            savePracticalAchievementFile.setFUploadTime(uploadTime);
            savePracticalAchievementFile.setFPaId(paId);
            savePracticalAchievementFile.setFDelFlag(false);//默认未删除
            this.save(savePracticalAchievementFile);
        }
        return true;
    }

    @Override
    public boolean downloadFile(Integer fid) {
        fileDao.findFileByFileId(fid);
        return true;
    }

    @Override
    public List<PracticalAchievementFile> findFileByPaId(long paid) {
        System.out.println("fileurl:oooo" + fileDao.findFileByPaId(paid));
        return fileDao.findFileByPaId(paid);
    }

}
